package qc.module.iot.api.consumer;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import qc.common.core.constants.IotConstant;
import qc.module.iot.dto.MqIotPacketsMessageDto;
import qc.module.iot.service.IotFramePacketsService;

/**
 * Iot数据帧报文保存至数据库Consumer
 *
 * @author QuCheng Tech
 * @since 2025/11/18
 */
@Component
//@RefreshScope
@RocketMQMessageListener(
        topic = IotConstant.MQ_FRAME_PACKETS_TOPIC,
        consumerGroup = IotConstant.MQ_FRAME_PACKETS_CONSUMER_SAVETODB_GROUP
)
public class IotPacketsSaveToDBConsumer implements RocketMQListener<MqIotPacketsMessageDto> {
    private static final Logger logger = LoggerFactory.getLogger(IotPacketsParseConsumer.class);

    @Value("${qucheng.consumer.packets-save:false}")
    private boolean enable;

    //模块名称，用于在日志或显示中统一使用
    private static final String moduleName = "Iot报文消息保存至数据库";

    @Autowired
    IotFramePacketsService framePacketsService;

    @Override
    public void onMessage(MqIotPacketsMessageDto message) {
        logger.debug("onMessage " + moduleName + " 当前消费者状态为：" + (enable ? "启用" : "禁用"));

        if (enable == true) {
            //不需要对消息进行有效性验证，理论上消息内容都是有效的，均通过IotFramePacketsService中receive方法生成并发送
            if (message != null) {
                //判断发送至MQ的消息来源，如果是来源于数据库不需要进行保存（定时任务从数据库中去除的待解析的报文数据帧）
                if (message.isFromDb() == false) {
                    try {
                        //保存到数据库，通过消息触发的均为已经发送至MQ
                        String receiveResult = framePacketsService.save(message, true);
                        if (StringUtils.isBlank(receiveResult)) {
                            //成功
                            logger.debug("保存数据帧成功，记录ID[{}]，报文[{}]", message.getId(), message.getHex());
                        } else {
                            //失败
                            logger.warn("保存数据帧失败，记录ID[{}]，报文[{}]，提示信息[{}]", message.getId(), message.getHex(), receiveResult);
                        }
                    } catch (Exception ex) {
                        logger.error("保存数据帧异常，记录ID[{}]，报文[{}]，异常信息[{}]", message.getId(), message.getHex(), ex.getMessage());
                    }
                }
            }
        }
    }
}